import useAuthStore from "@/stores/useAuthStore"
import type { DirectiveBinding, ObjectDirective } from "vue"

const allPermission = '*:*:*'

const hasPermi: ObjectDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string[]>) {
    const { value } = binding
    const permissions: string[] | undefined = useAuthStore().userInfo?.permissions
    if (Array.isArray(value) && value.length > 0) {
      const hasPermissions = permissions?.some(permission =>
        permission === allPermission || value.includes(permission)
      )

      if (!hasPermissions) {
        el.parentNode?.removeChild(el)
      }
    } else {
      throw new Error('请设置操作权限标签值')
    }
  }
}

export default hasPermi
